var path = window.location.pathname;
var user_auth = $("#user_auth").val();
var USERAUTH = getCookie('USERAUTH');
document.write('<scr' + 'ipt type="text/javascript" src="/js/functions/javascript_file.js" ></scr' + 'ipt>'); // Counter

function get_browser() {
    var N = navigator.appName, ua = navigator.userAgent, tem;
    var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null)
        M[2] = tem[1];
    M = M ? [M[1], M[2]] : [N, navigator.appVersion, '-?'];
    return M[0];
}
function get_browser_version() {
    var N = navigator.appName, ua = navigator.userAgent, tem;
    var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if (M && (tem = ua.match(/version\/([\.\d]+)/i)) != null)
        M[2] = tem[1];
    M = M ? [M[1], M[2]] : [N, navigator.appVersion, '-?'];
    return M[1];
}

// Browser Detection
var browser_name = get_browser();
var browser_version = get_browser_version()

var IE_version = "9"; // For Internet Explore Allow browser IE 9 - 10.
var moz_version = "20"; // For Mozilla FireFox Allow browser 21 Up.
var chrome_version = "27"; // For Google Chrome Allow browser 27 Up.

if(browser_name == "MSIE"){
    var console = {
        log : function(){
            return;
        }
    }
}

if (browser_name == "MSIE" && browser_version < IE_version) {
    window.location.replace("https://www.google.com/intl/en/chrome/browser/?hl=en&brand=CHMA&utm_campaign=en&utm_source=en-ha-sea-ph-bk&utm_medium=ha");
} else {
    if (browser_name == "Firefox" && browser_version < moz_version) {
        window.location.replace("https://www.google.com/intl/en/chrome/browser/?hl=en&brand=CHMA&utm_campaign=en&utm_source=en-ha-sea-ph-bk&utm_medium=ha");
    } else {
        if (browser_name == "Chrome" && browser_version < chrome_version) {
            window.location.replace("https://www.google.com/intl/en/chrome/browser/?hl=en&brand=CHMA&utm_campaign=en&utm_source=en-ha-sea-ph-bk&utm_medium=ha"); //alert($.browser.version)
        }
    }
}



if (path != "/login" || path != "/index" || path != "/user_view/index") {
    $(".oLayout").attr("href", null);
}

if (path == "/" || path == "/login" || path == "/index" || path == "/user_view/index") {
    $(".oLayout").attr("href", "/css/layout2.css");
}
//idleTime = 0;
$(document).ready(function() {
    // Preview for uploading
    $(".upfile").change(function(){
	readURL(this,".imagePrev");
    });
    
    var user_path = $("#user_url_view").val();
    if (path != "/login" || path != "/index" || path != user_path + "index") {
	$(".oLayout").attr("href", null);
    }
    
    if (path == "/" || path == "/login" || path == "/index" || path == user_path + "index") {
	$(".oLayout").attr("href", "/css/layout2.css");
    }
    
    //console.log(user_path + "==" + path)
    
    $("img").error(function() {
        if(path.match(/user_view/g) != null){

        }else{
            $(this).unbind("error").attr("src", "/images/error/broken.png");
        }
    });

    PostPrivacy.init();
    // UI Right Bar
    $("#company-announcement-container").perfectScrollbar();


    //Increment the idle time counter every minute.
    var pathname = window.location.pathname;
    //console.log(pathname+"!=/ && "+ pathname+"!=/login");
    // if (pathname!="/" && pathname!="/login") {
    // 	var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute
    //// 	//Zero the idle timer on mouse movement.
    // 	$(this).mousemove(function (e) {
    // 	    //idleTime = 0;
    //	    reset();
    // 	});
    // 	$(this).keypress(function (e) {
    //// 	    //idleTime = 0;
    // 	    reset();
    // 	});
    // }


    //for form list
    $("body").on("click", ".update_status_form", function() {
        var status = $(this).attr("data-status");
        var id = $(this).attr("data-id")
        updateStatus(status, "form", id);
    })
    $("body").on("click", ".delete_form", function() {
        var id = $(this).attr("data-form-id")
        delete_form("form", id, $(this));
    })
    //for orgchart list
    $("body").on("click", ".update_status_orgchart", function() {
        var status = $(this).attr("data-status");
        var id = $(this).attr("data-id")
        updateStatus(status, "orgchart", id);
    })
    $("body").on("click", ".delete_orgchart", function() {
        var id = $(this).attr("data-id")
        delete_form("orgchart", id, $(this));
    })
    //for workflow list
    $("body").on("click", ".update_status_workflow", function() {
        var status = $(this).attr("data-status");
        var id = $(this).attr("data-id")
        updateStatus(status, "workflow", id);
    })

    //for report list
    $("body").on("click", ".update_status_report", function() {
        var status = $(this).attr("data-status");
        var id = $(this).attr("data-id")
        updateStatus(status, "report", id);
    })
    $("body").on("click", ".delete_workflow", function() {
        var id = $(this).attr("data-id")
        delete_form("workflow", id, $(this));
    })
    //end

    $("body").on("click",".delete_printReport",function(){
        var id = $(this).attr("data-id")
        delete_form("print_report", id, $(this));
    })
    // Expand Sub Menu on Dashboard
    $("body").on("click", "li > .subClosed", function() {
        $(this).next().slideToggle();
    });

    // Window detect if browser resize
    if ($(window).width() < 1260) {
        //console.log("Close" + $(window).width());
        // Functions for close panel settings
        var pos = {
            pos_top_action: "-212",
            pos_top_prop_action: "0"
        }
        form_settings(this, ".form_properties", ".form_properties_actions", "form_settings_close", "form_settings_open", pos);

    } else {
        //console.log("Open" + $(window).width());
        // Functions for open panel settings
        var pos = {
            pos_top_action: "0",
            pos_top_prop_action: "211"
        }
        form_settings(this, ".form_properties", ".form_properties_actions", "form_settings_open", "form_settings_close", pos);

    }

//    $(window).on("resize",function() {
//        if ($(window).width() < 1260) {
//            console.log("Close" + $(window).width());
//	    $(".welcome").hide();
//            // Functions for close panel settings
//            var pos = {
//		pos_top_action : "-212",
//		pos_top_prop_action : "0"
//	    }
//	    form_settings(this,".form_properties",".form_properties_actions","form_settings_close","form_settings_open",pos);
//	    
//        } else {
//            console.log("Open" + $(window).width());
//	    $(".welcome").show();
//            // Functions for open panel settings
//	    var pos = {
//		pos_top_action : "0",
//		pos_top_prop_action : "211"
//	    }
//	    form_settings(this,".form_properties",".form_properties_actions","form_settings_open","form_settings_close",pos);
//            
//        }
//	
//    });	

    // Scrolling
    //$(window).scroll(function(){
    //    if ($(window).scrollTop() == $(document).height() - $(window).height()){
    //        alert(1)
    //    }
    //});

    // Detect if your using mobile devices or not..
    if (jQuery.browser.mobile) {
        console.log('You are using a mobile device!');
    } else {
        console.log('You are not using a mobile device!');
    }
    // hide #back-top first
    jQuery(".back-to-top").hide();

    // fade in #back-top
    jQuery(function() {
        jQuery(window).scroll(function() {
            if (jQuery(this).scrollTop() > 1000) {
                jQuery('.back-to-top').fadeIn();
            } else {
                jQuery('.back-to-top').fadeOut();
            }
        });

        // scroll body to 0px on click
        jQuery('.back-to-top a').click(function() {
            jQuery('body,html,header').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    });

    // get file path
    $("body").on("change", ".upfile", function() {
        var action = $(this).attr("data-action-id");
        var fpath = $(this).val().replace(/\\/g, '/');
        var a = fpath.split("/");
        var aParameter = a.length;
        //var fnameLength = fname.length;
        $("#uploadFilename_" + action).html("Filename: " + a[aParameter - 1]);

    });

    // Slide Show
    $("#slideshow > div:gt(0)").hide();

    setInterval(function() {
        $('#slideshow > div:first')
                .fadeOut(1000)
                .next()
                .fadeIn(1000)
                .end()
                .appendTo('#slideshow');
    }, 5000);

    // Tooltip
    $("a, .userAvatar, .tip").tooltip();

    // Message Menu
    $(".menuDropdown").on({
        "mouseenter": function() {
            var action = $(this).attr("data-action");
            if (action == "task") {
                var elements = "menu_task";
            } else if (action == "msg") {
                var elements = "menu_msg";
            } else if (action == "account") {
                var elements = "account_msg";
            }
            $("." + elements).stop(false, false).animate({
                "height": "toggle"
            }, 500);
        },
        "mouseleave": function() {
            var action = $(this).attr("data-action");
            if (action == "task") {
                var elements = "menu_task";
            } else if (action == "msg") {
                var elements = "menu_msg";
            } else if (action == "account") {
                var elements = "account_msg";
            }
            $("." + elements).stop(false, false).animate({
                "height": "toggle"
            }, 500);
        }
    });

    // Tabs
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active");
        $(this).addClass("active");
        $(".tab_content").removeClass('display').hide();
        var activeTab = $(this).attr("rel");
        $("#" + activeTab).addClass('display').show();
    });


    // Scroll show scroll top
    $(window).scroll(function() {
        var wTop = $(window).scrollTop();
        if (wTop > 500) {
            $(".scrollup").fadeIn().show();

        } else {
            $(".scrollup").fadeOut();
        }
    });
    $(".scrollup").click(function() {
        $("html, body").animate({scrollTop: 0}, 600);
        return false;
    });

    // Disable Right Click
    // $(document)[0].oncontextmenu = function() { return false;}

    //       $("body").mousedown(function(e){
    //         if( e.button == 2 ) {
    ////            jAlert( 'Sorry, this functionality is disabled!', "","", "", "", function(){})
// 		alert('Sorry, this functionality is disabled!');
    //            return false;
    //          } else {
    //            return true;
    //           }
    //       });
    //       window.addEventListener("keydown", keyListener, false);

    //       function keyListener(e) {
    //               if(e.keyCode == 123) {
    //                       e.returnValue = false;
    //               }
    //       }

    /*
     * Workspace Functions
     */
    workspace_functions.preview_form(".preview_form");

    // Choose form to create a workflow
    // $("body").on("click",".getForm",function(){



    // 	//window.location="/workflow";
    // })
    $("body").on("click", ".request-redirect", function() {
        var request_id = $(this).attr("request-id");
        var form_id = $(this).attr("form-id");
        window.location = "/workspace?view_type=request&formID=" + form_id + "&requestID=" + request_id;
    });
    hoverRotate();

    // Save coords of the user
    if (window.location.pathname === "/index" || window.location.pathname === "/login" || window.location.pathname === "/") {
        var c = function(pos) {
            var lat = pos.coords.latitude,
                    long = pos.coords.longitude,
                    acc = pos.coords.accuracy,
                    coords = lat + ', ' + long;
            $(".userCoords").val(coords);
            document.getElementById('google_map').setAttribute('src', 'https://maps.google.co.uk/?q=' + coords + '&z=60&output=embed');
        }

        navigator.geolocation.getCurrentPosition(c, e, {
            enableHighAccuracy: true
                    //timeout: 1
        })
    }
});


/*
 * functions
 * limitText(attribute,num)
 * @attribute - either class or ID /name
 * @num - number of string to show
 */
function limitText(attribute, num) {
    $(attribute).text(function(index, text) {
        if (num >= text.length) {
            return text.substr(0, num);
        } else {
            return text.substr(0, num) + " ....";
        }
    });
}

/*
 * Load More Function on the post
 * @postID - last id of the loaded post.
 */

function loadMore(postID, lastModified) {
    var ret = "";
    ret += '<div class="padding_5">';
    ret += '<div class="more more_' + postID + '" data-date="' + lastModified + '" id="more_' + postID + '" data-id="' + postID + '" style="float: left;margin: 10px 0px; width:99%;height: 40px;cursor: pointer;border-radius:5px;">';
    ret += '<div id="moreLbl_' + postID + '" style="text-align: center;padding:10px;font-weight:bold; line-height:20px;">Load More</div>';
    ret += '<div  class="display" id="moreload_' + postID + '">';
    ret += '<center>';
    //ret += '<img src="/images/loader/loading.gif" style="margin-top: 5px;"/>';
   ret += '<div class="spinner">';
  ret += '<div class="bar1"></div>';
  ret += '<div class="bar2"></div>';
  ret += '<div class="bar3"></div>';
  ret +=  '<div class="bar4"></div>';
  ret +=  '<div class="bar5"></div>';
  ret +=  '<div class="bar6"></div>';
  ret += '<div class="bar7"></div>';
  ret += '<div class="bar8"></div>';
  ret += '<div class="bar9"></div>';
 ret +=  '<div class="bar10"></div>';
  ret += '</div>';
    ret += '</center>';
    ret += '</div>';
    ret += '</div>';
    ret += '</div>';
    return ret;
}

// Get Url Parameter
function getParametersName(name, pathname) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(pathname);
    if (results != null) {
        return results[1];
    }

}
$.urlParam = function(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    } else {
        return results[1] || 0;
    }
}

//update status

function delete_form(type, id, self) {
    var originalType = type;
    var message = "Are you sure you want to delete?";
    if (type == "form") {
        message = "Warning all workflows connected to this forms will also be deleted. Are you sure you want to delete?";
    }
   var newConfirm = new jConfirm(message, 'Confirmation Dialog', '', '', '', function(r) {
        if (r == true) {
            // ui.block();
            type = "delete_" + type;
            $.post("/ajax/updateStatus", {type: type, id: id}, function(data) {
                // ui.unblock();
                if(originalType=="orgchart"){
                    $(".dataTable_orgchart").dataTable().fnDestroy();
                    GetOrgchartDataTable.defaultData();
                }else if(originalType=="workflow"){
                    $(".dataTable_workflow").dataTable().fnDestroy();
                    GetWorkflowDataTable.defaultData();
                }else if(originalType=="form"){
                    $(".dataTable_form").dataTable().fnDestroy();
                    GetFormDataTable.defaultData();
                }else if(originalType=="print_report"){
                    $(".dataTable_custom_report").dataTable().fnDestroy();
                    GetCustomReportDataTable.defaultData();
                }
                self.closest(".supTicket").fadeOut(function() {
                    $(this).next().remove();
                    $(this).remove();
                })
            })
        }
    });
   newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
}
function updateStatus(status, type, id) {
    var conf = "Are you sure you want to " + getStatus_revert(status) + " ?";
   var newConfirm = new jConfirm(conf, 'Confirmation Dialog', '', '', '', function(r) {
        if (r == true) {
            ui.block();
            $.post("/ajax/updateStatus", {type: type, id: id, status: status}, function(data) {
                // if(type=="form"){

                // }else if(type=="orgchart"){

                // }else if(type=="workflow"){

                // }
                ui.unblock();

                window.location.reload();
                // console.log(data);
            })
        }
    });
    newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});   
}

// Functions for Detecting if user is idle, away or back

function timerIncrement() {

    // getReset(function(data){
    // 	idleTime =  parseInt(data) + 1;

    // 	// Update
    // 	$.ajax({
    // 		type	:	"POST",
    // 		url	:	"/ajax/idle",
    // 		data	:	{action:"update",idleTime:idleTime},
    // 		success	:	function(data){
    // 			//console.log(data);
    // 		}

    // 	});
    // 	//console.log("Time " + idleTime);
    // 	if (idleTime > 19) { // 20 minutes
    // 		window.location.replace("/user/logout");
    // 	    //window.location.replace("/user/logout");
    // 	//    jAlert('Please log in to continue', 'Not Logged In', '', '', '', function(ans){
    // 	//	    if(ans==true){
    // 	//		window.location.replace("/user/logout");
    // 	//	    }
    // 	//    });
    // 	}else{
    // 	    var timeout = $(this).val();
    // 	    setMessage("Timeout changed to: " + timeout);
    // 	    idle.setAwayTimeout(timeout);

    // 	}
    // })


}

function getReset(callback) {

    // $.ajax({
    // 	type	:	"POST",
    // 	url	:	"/ajax/idle",
    // 	data	:	{action:"getReset"},
    // 	success	:	function(data){
    // 		callback(data);
    // 	}

    // });
}
function reset() {
    // $.ajax({
    // 	type	:	"POST",
    // 	url	:	"/ajax/idle",
    // 	data	:	{action:"reset"},
    // 	success	:	function(data){
    // 		//console.log(data);

    // 	}

    // });
}
$(function() {
    function setMessage(msg) {
        //$('#ActivityList').append("<li>" + new Date().toTimeString() + ": " + msg + "</li>");
        //console.log(msg);
        var pathname = window.location.pathname;
        if (pathname != "/" && pathname != "/login") {
            switch (msg) {
                case "User away.":
                    //reset();
                    ////alert(1)
                    //$.ajax({
                    //	type	:	"POST",
                    //	url	:	"/ajax/idle",
                    //	data	:	{action:"userAway"},
                    //	success	:	function(data){
                    //		//console.log(msg);
                    //	}
                    //	
                    //});
                    break;

                case "User back.":
                    //reset();
                    //$.ajax({
                    //	type	:	"POST",
                    //	url	:	"/ajax/idle",
                    //	data	:	{action:"userBack"},
                    //	success	:	function(data){
                    //		//console.log(msg);
                    //	}
                    //	
                    //});
                    break;

                case "User is not looking at the page.":
                    //reset();
                    //$.ajax({
                    //	type	:	"POST",
                    //	url	:	"/ajax/idle",
                    //	data	:	{action:"userAway"},
                    //	success	:	function(data){
                    //		//console.log(msg);
                    //	}
                    //	
                    //});
                    break;

                case "User started looking at the page again.":
                    //reset();
                    //$.ajax({
                    //	type	:	"POST",
                    //	url	:	"/ajax/idle",
                    //	data	:	{action:"userBack"},
                    //	success	:	function(data){
                    //		console.log(msg);
                    //	}
                    //});
                    break;

            }
        }
    }
    var awayCallback = function() {
        setMessage("User away.");
    };
    var awayBackCallback = function() {
        setMessage("User back.");
    };
    var hiddenCallback = function() {
        setMessage("User is not looking at the page.");
    };
    var visibleCallback = function() {
        setMessage("User started looking at the page again.")
    };

    var idle = new Idle({
        onHidden: hiddenCallback,
        onVisible: visibleCallback,
        onAway: awayCallback,
        onAwayBack: awayBackCallback,
        awayTimeout: "5000" //away with default value of the textbox
    });

});
function bind_onBeforeOnload(status) {
    if (status == 0) {
        window.onbeforeunload = function() {
            // blank function do nothing
        }
    } else {
        window.onbeforeunload = function(e) {
            return 'You will lose any unsaved edits';
        };
    }
}
function json_length(json) {
    var ctr = 0;
    $.each(json, function(key, value) {
        ctr++;
    });
    return ctr;
}
/* Date Functions
 *
 * Set the date of the post and for the comment
 * dateTimeDate();
 * 
 */
function dateTimeDate() {
    var d = new Date();
    return d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + ' ' + d.getHours() + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
}
function dateFunc() {
    var d = new Date();
    return d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
}
function hoverRotate() {
    var animate_over = "";
    var i = 0;
    $(".depth").on({
        "mouseenter": function() {
            var self = this
            animate_over = setInterval(function() {
                $(self).css({
                    "background": "linear-gradient(" + i + "deg,  rgba(249,249,249,1) 1%,rgba(184,225,252,1) 26%,rgba(169,210,243,1) 32%,rgba(144,186,228,1) 41%,rgba(144,188,234,1) 46%,rgba(0,119,239,1) 51%,rgba(70,148,226,1) 52%,rgba(162,218,245,1) 62%,rgba(189,243,253,1) 70%,rgba(252,252,252,1) 100%)"
                            // "background":"radial-gradient(farthest-corner, rgba(249,249,249,1) 1%,rgba(184,225,252,1) 26%,rgba(169,210,243,1) 32%,rgba(144,186,228,1) 41%,rgba(144,188,234,1) 46%,rgba(0,119,239,1) 51%,rgba(70,148,226,1) 52%,rgba(162,218,245,1) 62%,rgba(189,243,253,1) 70%,rgba(252,252,252,1) 100%)",
                            // "transform":"rotate("+i+"deg)"
                });
                if (i == 360) {
                    i = 0;
                }

                i += 1;
            }, 1)
        },
        "mouseleave": function() {
            clearInterval(animate_over);
            $(this).css({
                "background": ""
            })
        },
        "mousedown": function() {
            clearInterval(animate_over);
            $(this).css({
                "background": ""
            })
        }
    })
}

function brokenImage() {
    $("img").error(function() {
        $(this).unbind("error").attr("src", "/images/error/broken.png");
    });
}

function brokenUserImage() {
    $("img").error(function() {
        $(this).unbind("error").attr("src", "/js/functions/create_flowchart/adminnodes/avatardefault.jpg");
    });
}

var MD5 = function (string) {
 
    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }
 
    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
     }
 
     function F(x,y,z) { return (x & y) | ((~x) & z); }
     function G(x,y,z) { return (x & z) | (y & (~z)); }
     function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }
 
    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
 
    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
 
    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
 
    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };
 
    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };
 
    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };
 
    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
 
        for (var n = 0; n < string.length; n++) {
 
            var c = string.charCodeAt(n);
 
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
 
        }
 
        return utftext;
    };
 
    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;
 
    string = Utf8Encode(string);
 
    x = ConvertToWordArray(string);
 
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
 
    for (k=0;k<x.length;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }
 
    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 
    return temp.toLowerCase();
}


function popupwindow(url, title, w, h) {
  var left = (screen.width/2)-(w/2);
  var top = (screen.height/2)-(h/2)-50;
  return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}

function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0)
            return c.substring(name.length, c.length);
    }
    return "";
}


//New diolog theme

/*function removeFadeout(){
    $(this).animate({
        opacity:0
    },function(){
        $(this).remove();
    })
}*/
// Image preview functions
function readURL(input,target_loc) {
    if (input.files && input.files[0]) {
	var reader = new FileReader();
	reader.onload = function(e) {
	    //'#previewHolder'
	    $(target_loc).attr('src', e.target.result);
	}

	reader.readAsDataURL(input.files[0]);
    }
}

function removeFadeout(){
    $(this).not('#popup_overlay').addClass('fadeOutUp').queue(function() {  // Wait for 1 second.
            $(this).remove();
            $(".tooltip-arrow").closest(".tooltip").remove();
        });
    $('#popup_overlay').fadeOut(function(){
         $(this).remove();
         $(".tooltip-arrow").closest(".tooltip").remove();
    });

};

jDialog.prototype.themeDialog = function(themeVersion, options) {
    if (themeVersion == "modal2") {
        //alert($('#popup_container').length);

        var popCont = $('#popup_container');
        var closeDiolog = $('<div class="fl-closeDialog"><i class="fa fa-times"></i></div>');
        var clearBoth = $('<div class="clearfix"></div>');
        var footDialog = $('<div class="fl-footDialog"></div>');
        var dialogHeader = $('<div class="fl-dialogHeader"></div>');
        popCont.addClass('fadeInUp');
        popCont.addClass('fl-modal2');
        closeDiolog.on('click', function(){
            removeFadeout.call($(this).parents('#popup_container'));
            removeFadeout.call($('#popup_overlay'));
        });

        popCont.append(closeDiolog);
        popCont.append(footDialog);
        
        $('#popup_message').css('padding', '0px');
        $('#popup_message').children().filter(function(index){
           
            if (index == 0 || index == 1) {
                return true;

            }else {
                return false;
            }
        }).wrapAll(dialogHeader);

        $('#popup_message').children().filter(function(index){
            if ($(this).attr('style') == 'margin-top:-5px;font-size:11px;color:red') {
                return true;

            }else{
                return false;
            };
        }).css('margin', '5px 5px 0px');

        if (popCont.find('.content-dialog').length <= 0) {
             var wrapAllcontent = $('<div class="content-dialog"></div>')   
           popCont.find('#popup_message').children().not('.fl-dialogHeader').wrapAll(wrapAllcontent);
           popCont.find('.content-dialog').css('margin-bottom', '0px');
         };

        if (popCont.find('.fl-importBtn').length == 1) {
            var wrapperContentScroll = $('<div id="content-dialog-scroll"></div>');
             $('.content-dialog').wrap(wrapperContentScroll);
             $('.fl-importBtn').appendTo('#popup_message').not('h3');
             $('.fl-importBtn').css('margin', '0px 15px 15px 15px');
             $('div.uploader').css({
                'width':'auto', 
                'position':'static'
             });
         };


         if (popCont.find('#content-dialog-scroll').length <= 0) {
            var wrapperContentScroll = $('<div id="content-dialog-scroll"></div>');
            $('.content-dialog').wrap(wrapperContentScroll);
            $('#content-dialog-scroll').perfectScrollbar({
                  wheelSpeed: 20,
                  wheelPropagation: false,
                  suppressScrollX: true
            });         
         };  

         if (popCont.find('.addTabDialog').length == 1) {
                $('#content-dialog-scroll').css('height', 'auto');
         };
         if (popCont.find('.editTabDialog').length == 1) {
                 $('#content-dialog-scroll').css('height', 'auto');
         };


         if (popCont.find('.fl-get-workspace-popup').length == 1) {
             $('#content-dialog-scroll').css('height', 'auto');
             $('.fl-closeDialog').remove();  
         };

         if (popCont.find('.fl-end-workflow').length == 1) {
              $('#content-dialog-scroll').css('height', 'auto');
              $('.object_properties_wrapper').css('height', 'auto');
         };

         if (popCont.find('.middleware-settings-dialog').length == 1) {
            $('.middleware-settings-dialog').appendTo('#popup_message');
            dialogHeader.append('h3');
         };

        if (popCont.find('.trigger-container-fields').length == 1) {
            $('.trigger-container-fields').css('margin-top', '10px');
        };

        if (popCont.find('#clearValue').length == 1) {
            $('#clearValue').addClass('fl-buttonEffect');
            $('.content-dialog').css('margin-bottom', '0px');
        };

        if (popCont.find('.fl-filter-title').length == 1) {
            $('#content-dialog-scroll').css('height', 'auto');
            $('.content-dialog').css('margin-bottom', '0px');
        };

        if (popCont.find('.fl-remove-filter').length == 1) {
        };

        if (popCont.find('.forgot_submit ').length == 1) {
            $('#content-dialog-scroll').css('height', 'auto');
        };

        if (popCont.find('.fl-suggestion-input').length == 1 ) {
            $('#content-dialog-scroll').css('height', 'auto');
        };

        var Okbtn = $('.fl-dialogHeader').children().eq(1).children();
        Okbtn.addClass('fl-buttonEffect');
        footDialog.append(Okbtn);
        $('.fl-dialogHeader, .content-dialog').append(clearBoth);
        
        
        if ($('.jdiag-header-info-container').length == 1) {
            popCont.find('#popup_message').children().eq(0).append('<div class="header-info-header"><h3 class="fl-margin-bottom"><i class="fa fa-info-circle"></i> Header Information</h3></div>');  
            popCont.find('.jdiag-header-info-container').children('.header-info-header').remove();
            popCont.find('.jdiag-header-info-container').appendTo('#popup_message').next();
        };
        
     
        popCont.find('.hr').remove();
        popCont.find('h3').css('margin-bottom', '0px');
        popCont.find('#popup_cancel, .cancel-header-info').hide();
        popCont.find('.btn-blueBtn, .btn-basicBtn').appendTo(footDialog); 
        $(window).trigger('resize');   

         if (popCont.find('.fl-add-comment-here').length == 1) {
           popCont.find('i').addClass('faiconColor');
            if ($('#comment-container').length == 1) {
                $('#comment-container').children('#content-dialog-scroll').children('*').unwrap();
                popCont.find('#comment-container').css('top', '0px');
                popCont.find('.fl-above-addfiles').before(popCont.find('.fl-adding-comment, .btn-basicBtn').wrapAll('<div class="fl-addcom-addfile-wrapper fl-floatRight"></div>').parent());
            };
        };
        if (popCont.find('.fl-get-report').length == 1) {
            $('#content-dialog-scroll').css('height', 'auto');
            $('.content-dialog').css('margin-bottom', '0px');
        };

        if (popCont.find('#comment-container').length == 1) {
            $('#content-dialog-scroll').children().unwrap();
        };

        if (popCont.find('#fl-button-send-chat-attachments').length == 1) {
            $('#content-dialog-scroll').css('height', 'auto');
            $('.content-dialog').css('margin-bottom', '0px');
            popCont.find('.newMsg').remove();
        };


        if (popCont.find('input[type="button"]').length >= 1) {
                 popCont.find('input[type="button"]').on('click', function(){
                setTimeout(function(){
                     if ($('.error_bg').length >= 1) {
                            popCont.removeClass('fadeInUp');
                            popCont.addClass('tada');
                            setTimeout(function(){
                                popCont.removeClass('tada');
                            }, 500);
                    }
                 }, 500);
            });
        };
        if(options){
            if(options["height"]){
                // popCont.find(".content-dialog-scroll").eq(0).attr("style",popCont.attr("style")+"; height:"+options["height"]+"px !important");
                popCont.find(".content-dialog-scroll").eq(0).css("height",options["height"]+"px");
            };
        };

        /*if (popCont.find('.fl-requestImg').length == 1) {
            $('#content-dialog-scroll').css('height', 'auto');
            $('.content-dialog').css('margin-bottom', '0px');
        };*/
    };
};

jConfirm.prototype.themeConfirm = function(themeVersion, options){
    if (themeVersion == 'confirm2') {
         var popCont = $('#popup_container');
         var footDialog = $('<div class="fl-footDialog"></div>');
         var pop_panel = $('#popup_panel'); 
         var pop_message = $('#popup_message');
         popCont.addClass('bounceInUp');
         pop_message.prepend(options['icon']);
         pop_message.css({
            'padding': 10,
            'color':'#f00'
         });

         popCont.attr("jconfirmattr", "true");

         pop_panel.css({
            'padding-left': 0,
            'background-color':'transparent', 
            'padding': 0
         });

         popCont.append(footDialog);
         footDialog.append(pop_panel);
         
         if ($('#popup_ok').length == 1 || $('#popup_cancel').length == 1) {

                setTimeout( function(){
                        popCont.removeClass('bounceInUp');
                    },1000);
                popCont.find('#popup_ok').on('click', function(){
                    popCont.addClass('bounceOutUp');
                });
                popCont.find('#popup_cancel').on('click', function(){
                    popCont.addClass('bounceOutUp');
                });
         };
    };

};

jAlert.prototype.themeAlert = function(themeVersion){
    if (themeVersion == 'jAlert2') {

         var popCont = $('#popup_container');
         var footDialog = $('<div class="fl-footDialog"></div>');
         var pop_panel = $('#popup_panel'); 
         var pop_message = $('#popup_message');
         popCont.addClass('bounceInUp');
         pop_panel.css('background', 'transparent');
         popCont.append(footDialog);
         footDialog.append($('#popup_ok'));

    };
} 